package main

import (
	"fmt"
	"os"

	iCoreCache "core/contract/cache"
	iCoreDB "core/contract/db"
	iRrpc "core/contract/grpc"
	iCoreLog "core/contract/log"
	iCoreConfig "core/model/config"
	"core/service/cache"
	"core/service/db"
	"core/service/ioc"
	"core/service/log"
	"core/service/rpc"
	iResponse "gateway/contract/response"
	"gateway/router"
	ginSvc "gateway/service/gin"

	"github.com/spf13/viper"
)

var (
	config *iCoreConfig.Config
)

func main() {
	// 用于收集所有出现的错误
	var allErrors []error

	// 加载配置
	err := initConf()
	if err != nil {
		allErrors = append(allErrors, err)
	}

	dbFactory, deClearUp, err := db.NewDbFactory(config)
	if err != nil {
		allErrors = append(allErrors, err)
	}

	logFactory, err := log.NewLogFactory(config)
	if err != nil {
		allErrors = append(allErrors, err)
	}

	cacheFactory := cache.NewCacheFactory(&config.Cache)
	responseSvc := ginSvc.NewResponseSvc(logFactory)
	rpcFactory, rpcCleanUp, err := rpc.NewRpcFactory(config)
	if err != nil {
		allErrors = append(allErrors, err)
	}

	// 如果有任何错误发生，统一进行处理
	if len(allErrors) > 0 {
		panic(fmt.Errorf("以下错误发生：%v", allErrors))
	}

	defer func() {
		if dbFactory != nil {
			deClearUp()
		}
		if rpcFactory != nil {
			rpcCleanUp()
		}
	}()

	// 注册至ioc容器
	ioc.Set(new(iCoreDB.IDbFactory), dbFactory)
	ioc.Set(new(iCoreLog.ILogFactory), logFactory)
	ioc.Set(new(iCoreCache.ICacheFactory), cacheFactory)
	ioc.Set(new(iResponse.IResponse), responseSvc)
	ioc.Set(new(iRrpc.IGrpcFactory), rpcFactory)

	apiHandle := ginSvc.NewGinSvc(config, responseSvc)
	router.Register(apiHandle)
	apiHandle.Listen()
}

func initConf() error {
	wd, _ := os.Getwd()
	// 加载统一配置
	configPath := fmt.Sprintf("%s%s", wd, "/config/config.yaml")

	v := viper.New()
	v.SetConfigFile(configPath)
	err := v.ReadInConfig()
	if err != nil {
		return err
	}

	// 加载配置
	if err = v.Unmarshal(&config); err != nil {
		return err
	}
	fmt.Println(fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", 34, fmt.Sprintf("加载配置成功，配置是%+v", config)))

	return nil
}
